package gd.qaq.blue.powerparticle.utils;

import gd.qaq.blue.powerparticle.PowerParticle;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.util.HashMap;
import java.util.Map;

public class Particles {
    public static Map<String, BukkitTask> playersParticleTask = new HashMap<>();

    /**
     * 停止用户粒子效果
     *
     * @param p
     */
    public static void stopParticle(Player p) {
        BukkitTask bukkitTask = playersParticleTask.get(p.getUniqueId().toString());
        if (bukkitTask != null) {
            bukkitTask.cancel();
            playersParticleTask.remove(p.getUniqueId().toString());
        }
    }

    public static void spawnHelix(Player player, float r, float g, float b, double maxHealth) {
        stopParticle(player);
        float red = r / 255.0f;
        float green = g / 255.0f;
        float blue = b / 255.0f;
        BukkitTask bukkitTask = new BukkitRunnable() {
            double y = 0;
            int degree = 0;
            double needHealth = maxHealth;
            double lastMaxHealth = player.getMaxHealth();

            @Override
            public void run() {
                if (player == null || !player.isOnline() || player.getMaxHealth() < needHealth || player.getMaxHealth() != lastMaxHealth) {
                    stopParticle(player);
                    return;
                }
                for (int i = 10; i >= 0; i--) {
                    if (y < 2) {
                        if (degree < 360) {
                            double radians = Math.toRadians(degree);
                            double x = Math.cos(radians);
                            double z = Math.sin(radians);
                            Location location = player.getLocation();
                            location.add(x, y, z);
                            if (i % 2 == 0) {
                                player.getWorld().spigot().playEffect(location, Effect.COLOURED_DUST, 0, 1, red, green, blue, 1, 0, 30);
                            }
                            location.subtract(x, y, z);
                            degree += 1;
                        } else {
                            degree = 0;
                        }
                        if (y > 0.9) {
                            y += 0.0025;
                        } else if (y > 1.5) {
                            y += 0.0035;
                        } else {
                            y += 0.0015;
                        }
                    } else {
                        y = 0;
                        degree = 0;
                    }
                }
            }
        }.runTaskTimer(PowerParticle.plugin, 0, 0L);
        playersParticleTask.put(player.getUniqueId().toString(), bukkitTask);
    }
}
